package com.leef.glidetest.utils;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Leef on 2016/1/5.
 */
public class FileUtil {
    public static final int VOR = 0xAA;
    public static final int DEFAULT_BUFFER_SIZE = 8192;

    //  加密并拷贝
    public static void copyWithEncode(String in, String out, int vor) {
        try {
            FileInputStream fis = new FileInputStream(in);
            FileOutputStream fos = new FileOutputStream(out);

            byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
            int len = fis.read(buf);
            while (len != -1) {

                //  拷贝一份当前数据
                byte[] tmp = new byte[len];
                System.arraycopy(buf, 0, tmp, 0, len);
                //  将数据加密输出
                for (int j = 0; j < len; j++) {
                    tmp[j] = (byte) (tmp[j] ^ vor);
                }
                fos.write(tmp, 0, len);
                len = fis.read(buf);
            }

            fos.flush();
            fos.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //  解密并拷贝
    public static void copyWithDecode(String in, String out, int vor) {
        try {
            FileInputStream fis = new FileInputStream(in);
            FileOutputStream fos = new FileOutputStream(out);

            byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
            int len = fis.read(buf);
            while (len != -1) {

                //  拷贝一份当前数据
                byte[] tmp = new byte[len];
                System.arraycopy(buf, 0, tmp, 0, len);
                //  将数据解密输出
                for (int j = 0; j < len; j++) {
                    tmp[j] = (byte) (tmp[j] ^ vor);
                }
                fos.write(tmp, 0, len);
                len = fis.read(buf);
            }

            fos.flush();
            fos.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //  加密并拷贝
    public static void copy(String in, String out) {
        try {
            FileInputStream fis = new FileInputStream(in);
            FileOutputStream fos = new FileOutputStream(out);

            byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
            int len = fis.read(buf);
            while (len != -1) {
                fos.write(buf, 0, len);
                len = fis.read(buf);
            }

            fos.flush();
            fos.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
